<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!--    视口，调整页面适应移动端
                width=device-width：页面宽度与设备宽度一致
                initial-scale=1：初始缩放为1，即不会缩放
                minimum-scale=1：最小缩放比
                maximum-scale=1：最大缩放比
                user-scalable=no：用户自定缩放
        -->
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
    <title>书本购物车</title>
    <link href="../0918/bootstrap/css/bootstrap.css" rel="stylesheet">
    <!--    如下第三方库的JS一般写在head标签中-->
    <script src="../0918/js/jquery-3.5.1.js"></script>
    <script src="../0918/bootstrap/js/bootstrap.js"></script>
    <style>
        .collapse .navbar-nav {
            position: absolute;
            right: 0;
            top: -5px;
        }

        .breadcrumb {
            margin: 7px;
            display: inline-block;
        }

        .text-red {
            color: #FF0000;
        }

        .list-group-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .flex-content {
            display: flex;
            justify-content: space-between;
        }

        .jumbotron {
            background-color: white;
            border: solid 1px #ededed;
        }

        #content_div {
            padding: 0 15px 0 15px;
            margin-top: 0;
        }
    </style>
</head>
<body>
<div class="container">
    <!--    头部开始-->
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                        data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">书本商城</a>
            </div>

            <ol class="breadcrumb">
                <li><a href="#">Home</a></li>
                <li><a href="#">Library</a></li>
                <li class="active">Data</li>
            </ol>
            <span> Admin </span>
            <span class="text-red"> 欢迎您，系统管理员 </span>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                <ul class="nav navbar-nav">
                    <li class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
                           aria-expanded="false"><img width="30" src="img/systemAdministrator.jpg" class="img-circle">
                        </a>

                        <ul class="dropdown-menu">
                            <li><a href="#">个人信息</a></li>
                            <li role="separator" class="divider"></li>
                            <li><a href="#">注销</a></li>
                        </ul>
                    </li>
                </ul>
            </div><!-- /.navbar-collapse -->
        </div><!-- /.container-fluid -->
    </nav>
    <!--    头部结束-->
    <!--    中间内容-->
    <div class="row flex-content">
        <!--        左边菜单开始-->
        <div class="col-md-2" style="width: 210px;">
            <div class="list-group">
                <a href="#" class="list-group-item">
                    首页 <span class="glyphicon glyphicon-menu-right" aria-hidden="true"></span>
                </a>
                <a href="#" class="list-group-item active">书本商城 <span class="glyphicon glyphicon-menu-right"
                                                                      aria-hidden="true"></span></a>
            </div>
        </div>
        <!--        左边菜单结束-->
        <div class="col-md-9 col-sm-9 col-xs-9" style="flex: 1;margin: 0; padding: 0;">
            <div id="content_div" class="jumbotron">
                <h3>书本购物车</h3>
                <div class="panel panel-default">
                    <div class="panel-heading flex-content">
                        <form action="#" id="search_form" class="form-inline">
                            <div class="form-group input-group-sm">
                                <input type="text" class="form-control" name="name" placeholder="书名">
                            </div>
                            <div class="form-group input-group-sm">
                                <input type="number" class="form-control" name="minPrice" placeholder="最低价">
                            </div>
                            <div class="form-group input-group-sm">
                                <input type="number" class="form-control" name="maxPrice" placeholder="最高价">
                            </div>
                            <button type="button" class="btn btn-default btn-sm" onclick="doSearch()"><span
                                    class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
                        </form>
                        <div>
                            <button type="button" class="btn btn-sm btn-success" onclick="doAdd()">添加</button>
                            <button type="button" class="btn btn-sm btn-danger" onclick="doDelBatch()">批量删除</button>
                        </div>
                    </div>
                    <div class="panel-body">
                        <table id="table" class="table table-striped table-bordered table-hover">

                        </table>
                        <div class="flex-content" style="align-items: center;">
                            <div>
                                共<span id="pager_div_span" class="label label-danger">20</span>条记录
                            </div>
                            <nav aria-label="Page navigation">
                                <ul id="pager_ul" class="pagination">
                                    <li>
                                        <a href="#" aria-label="Previous">
                                            <span aria-hidden="true">&laquo;</span>
                                        </a>
                                    </li>
                                    <li class="active"><a href="#">1</a></li>
                                    <li><a href="#">2</a></li>
                                    <li><a href="#">3</a></li>
                                    <li><a href="#">4</a></li>
                                    <li><a href="#">5</a></li>
                                    <li>
                                        <a href="#" aria-label="Next">
                                            <span aria-hidden="true">&raquo;</span>
                                        </a>
                                    </li>
                                </ul>
                            </nav>
                            <select id="pager_select" class="form-control" style="width: auto;">
                                <option value="5">5</option>
                                <option value="10">10</option>
                                <option value="20">20</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="js/mock.js"></script>
<script>
    let books = [
        {id: 1, name: 'Java从入门到放弃', price: 80, createDate: '2020-07-01', count: 1},
        {id: 2, name: 'Vue从入门到放弃', price: 90, createDate: '2020-07-02', count: 1},
        {id: 3, name: 'Mysql从入门到放弃', price: 100.01, createDate: '2020-07-03', count: 1},
        {id: 4, name: '啥都从入门到放弃', price: 70.0001, createDate: '2020-07-04', count: 1},
        {id: 5, name: 'JavaScript从入门到放弃', price: 60.00, createDate: '2020-07-04', count: 1},
        {id: 6, name: 'JavaScript从入门到放弃', price: 50.00, createDate: '2020-07-04', count: 1}
    ];
    let Random = Mock.Random;
    Random.extend({
        getBookName: function () {
            let array = ["Java", "JavaScript", "Mysql", "JQuery", "HTML", "CSS", "Bootstrap",
                "Vue", "NodeJS", "React", "Less", "Express"];
            return this.pick(array);
        }
    })
    let data = Mock.mock({
        "books|100": [
            {
                "id|+1": 1,
                name: '@getBookName 从入门到放弃',
                price: '@float(60, 100, 0, 2)',
                createDate: '@date("yyyy-MM-dd")',
                count: "@integer(1, 20)"
            }
        ]
    });
    books = data.books;

    let table = document.querySelector("#table");
    let titles = ["<input type='checkbox' value='1' name='cb_select_all'>", "序号", "书名", "单价", "日期", "数量", "操作"];

    function createThead(titles, table) {
        if (!Array.isArray(titles)) {
            throw new Error("titles 必须是一个数组");
        }
        let thead = table.createTHead();
        let tr = document.createElement("tr");
        thead.appendChild(tr);
        titles.forEach(value => {
            let th = document.createElement("th");
            th.innerHTML = value;
            th.style.textAlign = "center";
            tr.appendChild(th);
        });
        let cb_select_all = tr.querySelector("input[name='cb_select_all']");
        cb_select_all.onchange = function (e) {
            let _self = this;
            table.querySelectorAll("input[name='cb_select']").forEach(item => item.checked = _self.checked);
        }
    }

    createThead(titles, table);

    function doDelBatch() {
        // console.log(table.querySelectorAll("input[name='cb_select']:checked"));
        // table.querySelectorAll("input[name='cb_select']").forEach()
        let ids = [];
        table.querySelectorAll("input[name='cb_select']:checked").forEach(item => {
            // books.splice(books.findIndex(value => value.id == item.getAttribute("data-index")), 1);
            // books = books.filter(value => value.id != item.getAttribute("data-index"));
            ids.push(parseInt(item.getAttribute("data-index")));
        });
        books = books.filter(value => ids.indexOf(value.id) == -1);
        updateTable(table, books);
        doPager(books);
    }

    /**
     * 分页实现
     */
    function doPager(data) {
        let pager_div_span = document.querySelector("#pager_div_span");
        let pager_select = document.querySelector("#pager_select");
        let pager_ul = document.querySelector("#pager_ul");

        pager_div_span.textContent = data.length;
        pager_select.onchange = function (e) {
            console.log(e.target.value);
            pageSize = parseInt(e.target.value);
            updateTable(table, books);
        }

        let count = data.length; // 数据的总量
        let pageTotal = Math.ceil(count / pageSize);// 一菜有多少页
        for (let i = 0; i < pageTotal; i++) {
            pager_ul.firstElementChild.insertAdjacentHTML("afterend", `<li onclick="changePageNum(${i + 1})"><a href="#">${i + 1}</a></li>`);
        }
    }

    function changePageNum(num) {
        pageNum = num;
        updateTable(table, books);
    }
    let pageSize = 5; // 一页显示的记录数量
    let pageNum = 4; // 控制当前的页码
    doPager(books);

    function doSearch() {
        // 获取搜索表单
        let search_form = document.querySelector("#search_form");
        let nameStr = search_form["name"].value;
        let minPrice = search_form["minPrice"].valueAsNumber;
        let maxPrice = search_form["maxPrice"].valueAsNumber;
        console.log(nameStr, minPrice, maxPrice);
        let searchData = books; // 符合搜索条件的数据
        if (nameStr.trim().length > 0) {
            searchData = searchData.filter(item => item.name.toLowerCase().indexOf(nameStr.toLowerCase()) != -1);
        }
        if (!isNaN(minPrice)) {
            searchData = searchData.filter(item => item.price >= minPrice);
        }
        if (!isNaN(maxPrice)) {
            searchData = searchData.filter(item => item.price <= maxPrice);
        }
        console.log(searchData);
        updateTable(table, searchData);
    }

    function createTBody(data, table) {
        if (!Array.isArray(data)) {
            throw new Error("data 必须是一个数组");
        }
        let tbody = table.createTBody();
        data.forEach((value, index) => {
            let tr = document.createElement("tr");
            tbody.appendChild(tr);
            tr.innerHTML = `
                <td><input type='checkbox' data-index="${value.id}" value='1' name='cb_select'></td>
                <td><span>${value.id}</span></td>
                <td data-editable><span>${value.name}</span><input hidden type="text" name="name" value="${value.name}"></td>
                <td data-editable><span>${value.price}</span><input hidden type="number" name="price" data-number="data-number" value="${value.price}"></td>
                <td data-editable><span>${value.createDate}</span><input hidden type="date" name="createDate" value="${value.createDate}"></td>
                <td data-editable><span>
                        <button type="button" onclick="optCount(event, -1, ${index})">-</button>
                         <span>${value.count}</span>
                         <button type="button" onclick="optCount(event, 1, ${index})" >+</button>
                    </span>
                    <input hidden type="number" name="count" data-number="data-number" value="${value.count}"></td>
                <td>
                    <div class="btn-group" role="group">
                      <button type="button" class="btn btn-primary" onclick="doEdit(event, ${index})">编辑</button>
                      <button type="button" class="btn btn-danger" onclick="doDel(event, ${index})">删除</button>
                    </div>
                </td>
            `;
        })
    }
    createTBody(books.filter((value, index) => index >= pageSize * (pageNum - 1) && index < pageSize * pageNum), table);

    function doEdit(e, index) {
        let tr = e.target.parentNode.parentNode.parentNode;
        let tds = tr.querySelectorAll("td[data-editable]");
        console.log(tds);
        tds.forEach(item => {
            item.firstElementChild.hidden = true;
            item.lastElementChild.hidden = false;
        });
        e.target.textContent = "保存";
        e.target.onclick = function (e) {
            // 获取编辑的对象
            let obj = books[index];
            // 获取所有输入框
            let inputs = tr.querySelectorAll("input");
            // 将输入框中的内容添加对象中
            inputs.forEach(item => {
                console.log(item.getAttribute("data-number"));
                if (item.getAttribute("data-number")) {
                    obj[item.name] = item.valueAsNumber;
                } else {
                    obj[item.name] = item.value;
                }
            })

            console.log(books);
            updateTable(table, books);
        }
        e.target.nextElementSibling.textContent = "取消";
        // console.log(e.target.nextElementSibling.onclick);
        let originClickFn = e.target.nextElementSibling.onclick;
        e.target.nextElementSibling.onclick = function (e) {
            tds.forEach(item => {
                item.firstElementChild.hidden = false;
                item.lastElementChild.hidden = true;
            });
            e.target.textContent = "删除";
            e.target.onclick = originClickFn;
        }
    }

    /**
     * @param e 事件对象
     * @param val 值
     * @param index 数据在数组中索引值
     */
    function optCount(e, val, index) {
        let span;
        if (val > 0) {
            // 加法
            span = e.target.previousElementSibling;
        } else {
            // 减法
            span = e.target.nextElementSibling;
        }
        // 减法时，数量不能小于0
        if ((books[index].count + val) < 0) {
            return;
        }
        // 同步到数组中的记录
        books[index].count = books[index].count + val;
        span.textContent = books[index].count;
        // console.log(books);
    }

    /**
     *  删除tbody
     */
    function clearTable(table) {
        table.tBodies[0].remove();
    }

    /**
     *  刷新表格
     */
    function updateTable(table, data) {
        clearTable(table);
        createTBody(data.filter((value, index) => index >= pageSize * (pageNum - 1) && index < pageSize * pageNum), table);
    }

    /**
     *
     *
     * */
    function doSave(e) {
        // 获取编辑的那个tr中所有的输入框
        let tr = e.target.parentNode.parentNode.parentNode;
        let inputs = tr.querySelectorAll("input");
        // 创建保存添加的数据的对象
        let obj = {};
        // 获取id最大值
        books.sort(function (o1, o2) {
            return o1.id - o2.id;
        });
        // 保存的数据的id是当前最大的id值+1
        obj.id = books[books.length - 1].id + 1;
        // 将obj添加到数组中
        // 将输入框中的内容保存到对象obj中
        inputs.forEach(item => {
            obj[item.name] = item.value;
        })
        // console.log(obj);
        books.push(obj);
        console.log(books);
        updateTable(table, books);
    }

    /**
     * 添加功能
     */
    function doAdd() {
        // 定义一行的模板
        let muban = ["", "", `<input type="text" name="name" placeholder="请输入书名">`,
            `<input type="number" name="price" placeholder="请输入价格">`,
            `<input type="date" name="createDate" placeholder="请输入日期">`,
            `<input type="number" name="count" placeholder="请输入数量">`,
            `<div class="btn-group" role="group" aria-label="...">
                      <button type="button" class="btn btn-primary" onclick="doSave(event)">保存</button>
                      <button type="button" class="btn btn-danger" onclick="doDel(event)">删除</button>
                    </div>`];

        let tr = document.createElement("tr");
        table.tBodies[0].appendChild(tr);
        muban.forEach(value => {
            let td = document.createElement("td");
            td.style.textAlign = "center";
            td.innerHTML = value;
            tr.appendChild(td);
        })
    }

    // 删除功能
    function doDel(e, index) {
        // 获取触发事件的元素
        // let _self = e.target;
        // let tr = _self.parentNode.parentNode.parentNode;
        // tr.remove();
        e.target.parentNode.parentNode.parentNode.remove();
        if (index > -1) {
            books.splice(index, 1);
            updateTable(table, books);
            doPager(books);
        }
        console.log(books);
    }

</script>
</body>
</html>